import { NavBar, List, Button, Toast } from "antd-mobile";
import React from "react";
import "./UserCenter.less";
import axios from "axios";
import { useNavigate } from "react-router-dom";

export default function UserCenter(props) {
    //声明状态
    let [user, setUser] = React.useState({});
    //获得跳转的函数
    let navigate = useNavigate();
    //钩子
    React.useEffect(() => {
        async function fn() {
            //发送请求
            let result = await axios.post("/login/verify");

            if (result.data.code === 20000) {
                //获取数据
                // console.log(result);
                //保存数据  修改状态
                setUser(result.data.data);
            } else {
                //没有登录 跳转到登录页面
                window.location.href = "/login";
                // props.history.push('/login') // react-router-dom@5 不生效了
            }
        }

        fn();
    }, []);

    //声明函数
    const logout = async () => {
        let result = await axios.post("/logout", { _id: user._id });
        //判断
        if (result.data.code === 20000) {
            Toast.show({
                icon: "success",
                content: "退出成功",
            });
            //路由跳转
            navigate("/login");
        } else {
            Toast.show({
                icon: "fail",
                content: "退出失败, 请重试~~",
            });
        }
    };

    return (
        <div className="user-container">
            <NavBar back={null}>个人中心</NavBar>
            <div className="h-50"></div>

            {/* 头像部分 start */}
            <div className="profile">
                <img src={user.avatar} alt="" />
                <p>欢迎, 用户 {user.username}</p>
            </div>
            {/* 头像部分 end */}

            {/* 个人中心 start */}
            <div className="info">
                <List>
                    <List.Item>
                        <span>昵称</span>
                        <span>{user.nickName}</span>
                    </List.Item>
                    <List.Item>
                        <span>手机号</span>
                        <span>{user.phone}</span>
                    </List.Item>
                </List>
            </div>
            {/* 个人中心 end */}
            <div className="h-50"></div>
            <Button block color="danger" size="large" onClick={logout}>
                退出登录
            </Button>
        </div>
    );
}
